package com.kienbk1910.productmanager;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sourceforge.zbar.android.CameraTest.CameraTestActivity;
import net.sourceforge.zbar.android.CameraTest.ZBarConstants;


import com.kienbk1910.common.Commom;
import com.kienbk1910.model.Product;
import com.kienbk1910.productmanager.photo.BaseAlbumDirFactory;
import com.kienbk1910.productmanager.provider.DBHelper;
import com.kienbk1910.productmanager.provider.ProductProvider;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.AvoidXfermode.Mode;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class AddProductActivity extends Activity implements OnClickListener{
	private Button scanBarcode;
	private EditText etbarcode;
	private EditText extName;
	private EditText extManu;
	private EditText extCost;
	private EditText extCount;
	private EditText extNote;
	private ImageButton takePhoto;
	private Button btnSave;
	private Button btnCancel;
	private ImageView photo;
	Product product;
	public static final int SCANNER_RESULT = 111;
	public static final int REQUEST_IMAGE_CAPTURE = 1;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private BaseAlbumDirFactory mAlbumStorageDirFactory = null;
	private String mCurrentPhotoPath; 
	private String pathImage;
	private int mode;
	List<String> tmpPhoto = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_product);
		
		scanBarcode =(Button)findViewById(R.id.scanBarcode);
		etbarcode   =(EditText)findViewById(R.id.editBarcode);
		extName   =(EditText)findViewById(R.id.etx_name);
		extManu   =(EditText)findViewById(R.id.etx_manu);
		extCost   =(EditText)findViewById(R.id.etx_cost);
		extCount   =(EditText)findViewById(R.id.etx_count);
		extNote  =(EditText)findViewById(R.id.etx_note);
		takePhoto =(ImageButton)findViewById(R.id.takePhoto);
		btnSave =(Button)findViewById(R.id.btn_save);
		btnCancel =(Button)findViewById(R.id.btn_cancel);
		photo = (ImageView)findViewById(R.id.photo);
		scanBarcode.setOnClickListener(this);
		takePhoto.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		getActionBar().setDisplayHomeAsUpEnabled(true);
		 mode =getIntent().getIntExtra(Commom.MODE, Commom.NEW);
		if(mode == Commom.NEW){
			getActionBar().setTitle("Thêm sản phẩm");
		}
		else{
			getActionBar().setTitle("Chỉnh sửa thông tin");
			product =(Product) getIntent().getSerializableExtra(Commom.PRODUCT);

		
			etbarcode.setText(product.getBarcode());
			extName.setText(product.getName());
			extManu.setText(product.getManufacturer());
			extCost.setText(String.valueOf(product.getCost()));
			extCount.setText(String.valueOf(product.getCount()));
			extNote.setText(product.getNote());
			pathImage =product.getImagePath();
			Log.d("kienbk1910", pathImage);
			
		}
	}
@Override
	public boolean dispatchTouchEvent(MotionEvent ev)
	{
	    View v = getCurrentFocus();
	     
	    if (v != null && 
	            (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && 
	            v instanceof EditText && 
	            !v.getClass().getName().startsWith("android.webkit."))
	    {
	        int scrcoords[] = new int[2];
	        v.getLocationOnScreen(scrcoords);
	        float x = ev.getRawX() + v.getLeft() - scrcoords[0];
	        float y = ev.getRawY() + v.getTop() - scrcoords[1];
	 
	        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
	            hideKeyboard(this);
	    }
	    return super.dispatchTouchEvent(ev);
	}
	private static void hideKeyboard(Activity activity)
	{
	    if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null)
	    {
	        InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
	        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
	    }
	}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
	// TODO Auto-generated method stub
	super.onWindowFocusChanged(hasFocus);
	if (product != null &&product.getImagePath() != null
			&& product.getImagePath().length() > 0) {
		File imgFile = new File(product.getImagePath());
		if (imgFile.exists()) {
			setPic(pathImage);

		}
	}
}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.add_product, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		if(id ==android.R.id.home){
			for (String namphoto : tmpPhoto) {
				Commom.deleteFile(namphoto);
				
			}
			finish();
			overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.scanBarcode:
		
			Intent intent = new Intent(this, CameraTestActivity.class);
	          startActivityForResult(intent, SCANNER_RESULT);
			
			break;
	   case R.id.takePhoto:
		   dispatchTakePictureIntent();
		   break;
	
		case R.id.btn_save:
			saveProduct();
			break;
		case R.id.btn_cancel:
	
			for (String namphoto : tmpPhoto) {
				Commom.deleteFile(namphoto);
				
			}
			finish();
			overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
			break;
		default:	
			break;
		}
	}
	  @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
			super.onActivityResult(requestCode, resultCode, intent);
			/**
			 * Back from scanner view
			 */
			if (requestCode == SCANNER_RESULT) {
				if (resultCode == RESULT_OK) {
					String contents = intent.getStringExtra(ZBarConstants.SCAN_RESULT);
					etbarcode.setText(contents);
					/*Intent encodeIntent = new Intent("eu.michalu.ENCODE");  
					encodeIntent.addCategory(Intent.CATEGORY_DEFAULT); 
					encodeIntent.putExtra("ENCODE_FORMAT", "CODE_128");  
					encodeIntent.putExtra("ENCODE_DATA", contents);  
				    startActivity(encodeIntent); */

				} else if (resultCode == RESULT_CANCELED) {
					// Handle cancel
					Log.i(MainActivity.class.getSimpleName(), "Handle cancel");
					
				}
			}
			 if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
				pathImage =mCurrentPhotoPath;
				tmpPhoto.add(mCurrentPhotoPath);
				Log.d("kienbk1910", mCurrentPhotoPath);
				 handleBigCameraPhoto();
			    }
			 else{
				 Log.d("kienbk1910","errro");
				 Commom.deleteFile(mCurrentPhotoPath);
				
			 }
	    }
	  
	  // take photo
	  private void handleBigCameraPhoto() {

			if (mCurrentPhotoPath != null) {
				setPic(mCurrentPhotoPath);
				mCurrentPhotoPath = null;
			}

		}
	  private void setPic(String mCurrentPhotoPath) {

			/* There isn't enough memory to open up more than a couple camera photos */
			/* So pre-scale the target bitmap into which the file is decoded */

			/* Get the size of the ImageView */
		  Log.d("kienbk1910", "setpic");
			int targetW = photo.getWidth();
			int targetH = photo.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) || (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH);	
			}

			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;
			bmOptions.inPurgeable = true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			
			/* Associate the Bitmap to the ImageView */
			photo.setImageBitmap(bitmap);
	
		
		}
	  private void dispatchTakePictureIntent() {
		    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		    File f = null;
			
			try {
				f = setUpPhotoFile();
				mCurrentPhotoPath = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			} catch (IOException e) {
				e.printStackTrace();
				f = null;
				mCurrentPhotoPath = null;
			}
			startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
		}
	  private File createImageFile() throws IOException {
			// Create an image file name
			String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
			String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
			File albumF = getAlbumDir();
			File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
			return imageF;
		}

		private File setUpPhotoFile() throws IOException {
			
			File f = createImageFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			
			return f;
		}
		private File getAlbumDir() {
			File storageDir = null;

			if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
				storageDir = mAlbumStorageDirFactory.getAlbumStorageDir("photo");

				if (storageDir != null) {
					if (! storageDir.mkdirs()) {
						if (! storageDir.exists()){
							Log.d("CameraSample", "failed to create directory");
							return null;
						}
					}
				}
				
			} else {
				Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
			}
			
			return storageDir;
		}
		// save product;
		public void saveProduct(){
		
			Product product = new Product();
			if(extName.getText().length()<= 0){
				Toast.makeText(this, "Bạn thiếu tên sản phẩm", Toast.LENGTH_LONG).show();
				return;
			}
			product.setName(extName.getText().toString().trim());
			if(extManu.getText().length()<= 0){
				Toast.makeText(this, "Bạn thiếu tên nhà sản xuất", Toast.LENGTH_LONG).show();
				return;
			}
			product.setManufacturer(extManu.getText().toString().trim());
			if(extCost.getText().length()<= 0){
				Toast.makeText(this, "Bạn thiếu giá của sản phẩm", Toast.LENGTH_LONG).show();
				return;
			}
			product.setCost(Integer.parseInt(extCost.getText().toString().trim()));
			if(extCount.getText().length()<= 0){
				Toast.makeText(this, "Bạn thiếu số lượng của sản phẩm", Toast.LENGTH_LONG).show();
				return;
			}
			product.setCount(Integer.parseInt(extCount.getText().toString().trim()));
			if(extNote.getText().length()>0){
				product.setNote(extNote.getText().toString().trim());
			}
			if(etbarcode.getText().length()>0){
				product.setBarcode(etbarcode.getText().toString().trim());
			}
			if(pathImage != null){
				product.setImagePath(pathImage);
			}
			
			if(mode == Commom.NEW){
				if(product.getBarcode()!=null && product.getBarcode().length()>0 && Commom.checkBarCode(product.getBarcode(),this)){
					Toast.makeText(this, "Có lẽ sản phẩm đã tồn tại, trùng lập mã vạch", Toast.LENGTH_LONG).show();
					return;
				}
				if(tmpPhoto.size()>0)
					tmpPhoto.remove(tmpPhoto.size()-1);
				for (String namphoto : tmpPhoto) {
					Commom.deleteFile(namphoto);
					
				}
					addProduct(product);

			
				finish();
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
			}else{
				if(tmpPhoto.size()>0)
					tmpPhoto.remove(tmpPhoto.size()-1);
				for (String namphoto : tmpPhoto) {
					Commom.deleteFile(namphoto);
					
				}
				product.setId(this.product.getId());
				
				updateProduct(product);
				if (this.product.getImagePath() != null
						&& product.getImagePath().length() > 0 && !product.getImagePath().equalsIgnoreCase(this.product.getImagePath())) {
					File file = new File(this.product.getImagePath());
					if (file.exists()) {
						Log.d("kienbk1910", "delete file");
						boolean deleted = file.delete();
					}
				}
				Intent intent = new Intent();
				intent.putExtra(Commom.PRODUCT, product);
				setResult(Activity.RESULT_OK, intent);
				finish();
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
			}
		}
		 public void addProduct(Product product) {
		      // Add a new birthday record
		      ContentValues values = new ContentValues();
		      // requreid
		      values.put(DBHelper.NAME,product.getName());
		      values.put(DBHelper.MANUFACTURER,product.getManufacturer());
		      values.put(DBHelper.COST,product.getCost());
		      values.put(DBHelper.COUNT,product.getCount());
		      //option
		      if(product.getBarcode()!= null && product.getBarcode().length()>0){
		    	     values.put(DBHelper.BAR_CODE,product.getBarcode());
		      }
		      if(product.getNote()!= null && product.getNote().length()>0){
		    	     values.put(DBHelper.NOTE,product.getNote());
		      }
		      if(product.getImagePath()!= null && product.getImagePath().length()>0){
		    	     values.put(DBHelper.IMAGE_PATH,product.getImagePath());
		      }
		      Uri uri = getContentResolver().insert(
		    	ProductProvider.CONTENT_URI, values);
		      Toast.makeText(this, "Bạn đã thêm sản phẩm thành công!", Toast.LENGTH_SHORT).show();
		   }
		 public void updateProduct(Product product){
				String URL = ProductProvider.URL + "/" + product.getId();
				Uri friends = Uri.parse(URL);
				ContentValues values = new ContentValues();
			      // requreid
			      values.put(DBHelper.NAME,product.getName());
			      values.put(DBHelper.MANUFACTURER,product.getManufacturer());
			      values.put(DBHelper.COST,product.getCost());
			      values.put(DBHelper.COUNT,product.getCount());
			      //option
			      if(product.getBarcode()!= null && product.getBarcode().length()>0){
			    	     values.put(DBHelper.BAR_CODE,product.getBarcode());
			      }
			      if(product.getNote()!= null && product.getNote().length()>0){
			    	     values.put(DBHelper.NOTE,product.getNote());
			      }
			      if(product.getImagePath()!= null && product.getImagePath().length()>0){
			    	     values.put(DBHelper.IMAGE_PATH,product.getImagePath());
			      }
				int count = getContentResolver().update(friends, values, null,null);
		 }
		 
}
